package com.hontech.bvapp2.device.cp

import com.hontech.bvapp2.device.Address
import com.hontech.bvapp2.device.DeviceConn
import com.hontech.bvapp2.device.Frame
import com.hontech.bvapp2.utils.hex16
import com.hontech.bvapp2.utils.isBitSet
import com.hontech.bvapp2.utils.postEvent
import serial.codec.Uint16
import serial.codec.Uint8
import serial.codec.u8

private const val PARTS_CTRL = 0x04
private const val PICK_CTRL = 0x05
private const val STRAW_CTRL = 0x06

object Door {

    suspend fun strawCtrl(ctrl: Int) {
        DeviceConn.req(
            Address.DOOR,
            STRAW_CTRL,
            ctrl.u8()
        ).parse()
    }

    suspend fun pickCtrl(ctrl: Int) {
        DeviceConn.req(
            Address.DOOR,
            PICK_CTRL,
            ctrl.u8()
        ).parse()
    }

    suspend fun partsCtrl(id: Int, ctrl: Int) {
        DeviceConn.simpleReq(
            Address.DOOR,
            PARTS_CTRL,
            id.u8(),
            ctrl.u8()
        ).parse()
    }

    fun onStatus(frame: Frame) {
        val version = Uint16()
        val sensor = Uint8()
        val analog = Uint16()
        frame.parse(version, sensor, analog)
        val s = Status(
            version.value,
            sensor.value,
            analog.value
        )
        status = s
        postEvent(s)
    }

    var status: Status? = null
        private set

    class Status(
        val version: Int,
        val sensor: Int,
        val analog: Int,
    ) {

        fun version() = version.hex16()

        fun doorClose() = sensor.isBitSet(0)
        fun door2Close() = sensor.isBitSet(1)
        fun pickClose() = sensor.isBitSet(2)
        fun pickOpen() = sensor.isBitSet(3)
        fun pick2() = sensor.isBitSet(4)
        fun cupChecked() = sensor.isBitSet(5)
    }
}

